//
//  WebTest.m
//  IClothStore
//
//  Created by svp on 21/08/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "WebRequest.h"
#import "JsonFramework/SBJson.h"
#import "Utils.h"

@implementation WebRequest

@synthesize delegate = _delegate;

-(void) requestTo:(NSString*)uri withBody:(NSString*)httpBody
{
	NSString *host = [Utils getHostAddress];
	NSString *url = [NSString stringWithFormat:@"%@/%@/%@",host,WebServiceServer,uri];
	NSLog(@"AAAA:%@",url);
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url]];
	[request setHTTPMethod:@"POST"];
	[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:[httpBody dataUsingEncoding:NSUTF8StringEncoding]];
	
	
	theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self ]; 
	
	if (theConnection) {
		
		receivedData = [[NSMutableData data] retain];
		
	} else {
		
		
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
	
    NSLog(@"connection didReceiveResponse");
	
    [receivedData setLength:0];
	
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{	
		
	NSLog(@"connection didReceiveData");
	
    [receivedData appendData:data];
	
}

- (void)connection:(NSURLConnection *)connection  didFailWithError:(NSError *)error

{
	
    [connection release];
	
    [receivedData release];
	
    NSLog(@"Connection failed! Error - %@ %@",
		  
          [error localizedDescription],
		  
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
	[self notifyIfConnectionFail:error];
	
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	
	NSString* returnString= [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];
	
	
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

	NSLog(@"receive data: %@",returnString);
	
	SBJsonParser *parser = [[SBJsonParser alloc] init];
	NSDictionary *object = [parser objectWithString:returnString error:nil];
	NSLog(@"%@",object);
	
	[self processResult:object];

    [connection release];
	
    [receivedData release];
	
}

-(void) dealloc
{
	NSLog(@"webtest dealloc");
	[theConnection release];
	[receivedData release];
	[super dealloc];
}

-(void) processResult:(NSDictionary*)result
{
}

-(void) notifyIfConnectionFail:(NSError*)error
{
}


@end
